package cn.tedu.zx.sso.security.service.amdin;

import cn.tedu.zx.common.exception.ServiceException;
import cn.tedu.zx.pojo.admin.entity.Admin;
import cn.tedu.zx.sso.mapper.admin.AdminMapper;
import cn.tedu.zx.sso.mapper.admin.PermissionMapper;
import cn.tedu.zx.sso.pojo.entity.AdminAuthority;
import cn.tedu.zx.sso.pojo.entity.AdminUserDetails;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class AdminSSOUserDetailsService implements UserDetailsService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //获取与用户名匹配的管理员信息
        Admin admin = null;

        try {
            admin = adminMapper.findByUsername(username);
        } catch (ServiceException e) {
            throw new BadCredentialsException("登录失败，用户名不正确");
        }
        if (admin==null){
            return null;
        }
        //检查管理员是否占用
        if (admin.getIsEnable()!=1){
            throw new BadCredentialsException("登录失败，用户账号已被禁用");
        }
        //获取管理员的权限列表
        List<String> permissions = permissionMapper.findPermissionsByAdminId(admin.getId());
        List<AdminAuthority> authorities=new ArrayList<>();
        for (String permission : permissions) {
            AdminAuthority authority = new AdminAuthority();
            authority.setValue(permission);
            authorities.add(authority);
        }
        AdminUserDetails userDetails = new AdminUserDetails();
        BeanUtils.copyProperties(admin,userDetails);
        userDetails.setAuthorities(authorities);
        //返回
        log.info("{}",userDetails);
        return userDetails;
    }
}
